package com.cskaoyan.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cskaoyan.bean.*;
import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.sysmanage.*;
import com.cskaoyan.exception.MarketException;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.ConstantPropertiesUtils;
import com.cskaoyan.utils.FileUtils;
import com.cskaoyan.utils.Md5Utils;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    StorageMapper storageMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    SystemPermissionMapper systemPermissionMapper;

    @Override
    public AdminPageData query(String username, BaseParam baseParam) {
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        List<Admin> admins = adminMapper.selectByExample(example);

        return AdminPageData.ok(admins);
    }

    @Override
    public OptionsVo queryAllRole() {
        RoleExample example = new RoleExample();
        List<Role> roles = roleMapper.selectByExample(example);
        return OptionsVo.ok(roles);
    }

    @Override
    public StorageVo addStorage(MultipartFile file) throws MarketException {
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        Storage storage = new Storage();
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();
            String filename = "";

            String originalFilename = file.getOriginalFilename();
            //uuid 添加唯一值，使文件名不重复
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //文件拓展名
            String fileExtensionName = FileUtils.getFileExtensionName(originalFilename);
            filename = uuid + "." + fileExtensionName;
            storage.setKey(filename);

            //根据日期进行分类
            String dataPath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            if ("xls".equals(fileExtensionName) || "xlxs".equals(fileExtensionName)) {
                filename = "Excel/" + dataPath + "/" + filename;
            } else {
                filename = dataPath + "/" + filename;
            }


            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            storage.setUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


        storage.setName(file.getOriginalFilename());
        storage.setType(file.getContentType());
        storage.setSize(((int) file.getSize()));
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());

        int insertRow = storageMapper.insertSelective(storage);
        if (insertRow <= 0) {
            throw new MarketException("头像上传失败");
        }

        //头像上传成功
        Storage storageInfo = storageMapper.selectByKey(storage.getKey());
        StorageVo storageVo = new StorageVo();
        storageVo.setId(storageInfo.getId());
        storageVo.setKey(storageInfo.getKey());
        storageVo.setName(storageInfo.getName());
        storageVo.setType(storageInfo.getType());
        storageVo.setSize(storageInfo.getSize());
        storageVo.setUrl(storageInfo.getUrl());
        storageVo.setAddTime(storageInfo.getAddTime());
        storageVo.setUpdateTime(storageInfo.getUpdateTime());
        return storageVo;
    }

    @Override
    public boolean queryAdminByUserName(String username) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        List<Admin> admins = adminMapper.selectByExample(example);
        if (admins == null || admins.size() == 0) {
            return false;
        }
        return true;
    }

    @SneakyThrows
    @Override
    public boolean addAdmin(AddAdminBo addAdminBo) {
        Admin admin = new Admin();
        admin.setUsername(addAdminBo.getUsername());
        //密码加密
        String password = Md5Utils.getMd5(addAdminBo.getPassword(), "password");
        admin.setPassword(password);
        //admin.setPassword(addAdminBo.getPassword());
        admin.setAvatar(addAdminBo.getAvatar());
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        admin.setRoleIds(addAdminBo.getRoleIds());
        int insertRows = adminMapper.insertSelective(admin);
        return insertRows == 1;
    }

    @Override
    public Admin queryAdminById(Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        return admin;
    }

    @SneakyThrows
    @Override
    public boolean updateAdmin(UpdateAdminBo updateAdminBo) {
        Admin admin = new Admin();
        admin.setId(updateAdminBo.getId());
        admin.setUsername(updateAdminBo.getUsername());
        //密码加密
        String password = Md5Utils.getMd5(updateAdminBo.getPassword(), "password");
        admin.setPassword(password);
        //admin.setPassword(updateAdminBo.getPassword());
        admin.setAvatar(updateAdminBo.getAvatar());
        admin.setUpdateTime(new Date());
        admin.setRoleIds(updateAdminBo.getRoleIds());
        int insertRows = adminMapper.updateByPrimaryKey(admin);
        return insertRows == 1;
    }

    @Override
    public boolean deleteAdmin(Integer id) {
        int deleteRows = adminMapper.deleteByPrimaryKey(id);
        return deleteRows == 1;
    }

    @Override
    public List<Admin> selectAdminByRolesId(Integer rolesId) {
        List<Admin> admins = adminMapper.selectByRolesId(rolesId);
        return admins;
    }

    @Override
    public String selectPwdByName(String username) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        List<Admin> admins = adminMapper.selectByExample(example);
        return admins.size() >= 1 ? admins.get(0).getPassword() : null;
    }

    @Override
    public List<String> selectSysPermissionByUserName(String username) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        List<Admin> admins = adminMapper.selectByExample(example);
        if (admins.size() >= 1) {
            Admin admin = admins.get(0);
            Integer[] roleIds = admin.getRoleIds();
            PermissionExample permissionExample = new PermissionExample();
            PermissionExample.Criteria criteria1 = permissionExample.createCriteria();
            if (roleIds.length > 0) {
                criteria1.andRoleIdIn(Arrays.asList(roleIds));
            }
            List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
            ArrayList<String> strings = new ArrayList<>();
            for (Permission permission : permissions) {
                String permissionInfo = permission.getPermission();
                strings.add(permissionInfo);
            }
            ArrayList<String> apiList = new ArrayList<>();
            SystemPermissionExample systemPermissionExample = new SystemPermissionExample();
            SystemPermissionExample.Criteria sysPerCriteria = systemPermissionExample.createCriteria();
            if(strings == null || strings.size() == 0){
                return null;
            }
            sysPerCriteria.andPermissionIdIn(strings);
            List<SystemPermission> systemPermissions = systemPermissionMapper.selectByExample(systemPermissionExample);
            for (SystemPermission systemPermission : systemPermissions) {
                String api = systemPermission.getApi();
                apiList.add(api);
            }
            return apiList;

        }
        return null;
    }

    @Override
    public Admin selectAdminByUsername(String username) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        List<Admin> admins = adminMapper.selectByExample(example);
        return admins.size() >= 1 ? admins.get(0) : null;
    }

    @Override
    public List<String> selectRolesByUsername(String username) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameEqualTo(username);
        }
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins.size() <= 0) {
            return null;
        }
        Admin admin = admins.get(0);
        Integer[] roleIds = admin.getRoleIds();
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria roleCriteria = roleExample.createCriteria();
        if (roleIds != null && roleIds.length > 0){
            roleCriteria.andIdIn(Arrays.asList(roleIds));
        }
        List<Role> roles = roleMapper.selectByExample(roleExample);
        List<String> rolesResult = new ArrayList<>();
        for (Role role : roles) {
            String name = role.getName();
            rolesResult.add(name);
        }
        return rolesResult;
    }

    @Override
    public List<String> selectPermissionById(Integer id) {
        Admin admin = adminMapper.selectByPrimaryKey(id);
        Integer[] roleIds = admin.getRoleIds();
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria roleCriteria = permissionExample.createCriteria();
        if (roleIds != null && roleIds.length > 0){
            roleCriteria.andRoleIdIn(Arrays.asList(roleIds));
        }
        List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
        List<String> permissionResult = new ArrayList<>();
        for (Permission permission : permissions) {
            String permission1 = permission.getPermission();
            permissionResult.add(permission1);
        }
        return permissionResult;

    }

    @Override
    public void updateAdminLastLoginIp(Integer id, String remoteAddr) {
        Admin admin = new Admin();
        admin.setId(id);
        admin.setLastLoginIp(remoteAddr);
        admin.setLastLoginTime(new Date());
        admin.setUpdateTime(new Date());
        adminMapper.updateByPrimaryKeySelective(admin);
    }


}
